package com.cloudcc.mobile.view.activity;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.CallLog;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudcc.cloudframe.CApplication;
import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.bus.IEventLife;
import com.cloudcc.cloudframe.ui.viewgroup.loadmore.LoadMoreContainer;
import com.cloudcc.cloudframe.ui.viewgroup.refresh.PtrFrameLayout;
import com.cloudcc.cloudframe.util.DateUtils;
import com.cloudcc.mobile.ExtraConstant;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.adapter.CallLogAdapter;
import com.cloudcc.mobile.dao.CallLogDao;
import com.cloudcc.mobile.dao.impl.CallLogDaoImpl;
import com.cloudcc.mobile.dialog.CallLogLoadingDialog;
import com.cloudcc.mobile.dialog.CallOutDialog;
import com.cloudcc.mobile.entity.CallLogEntity;
import com.cloudcc.mobile.entity.CallLogMatchEntity;
import com.cloudcc.mobile.entity.JurisdictionEntity;
import com.cloudcc.mobile.entity.MoreJurisdictionEntity;
import com.cloudcc.mobile.event.BeauEventList;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.view.base.BaseActivity;
import com.cloudcc.mobile.widget.listview.CloudCCListView;
import com.litesuits.android.log.Log;
import com.mypage.utils.AnimViewUtils;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by lin on 2017/6/2.
 * <p>
 * 通话记录页面
 */

public class CallLogActivity extends BaseActivity implements IEventLife, View.OnClickListener, CloudCCListView.OnRefreshOrLoadMoreListener, AdapterView.OnItemClickListener {

    @Bind(R.id.top_back)
    ImageView topBack;
    @Bind(R.id.top_more)
    ImageView topMore;
    @Bind(R.id.top_title)
    TextView topTitle;
    @Bind(R.id.call_log_listview)
    CloudCCListView callLogListview;
    @Bind(R.id.call_log_empty)
    LinearLayout callLogEmpty;


    private List<CallLogEntity> lists , listsNew, listall;//listall是从本地通话记录读取的50条信息列表 ， listsnew是请求服务器匹配后的数据列表，用于listview的展示，  lists是分页加载的本地数据
    private CallLogAdapter adapter;
    private int Pager = 0;//标记分页，每页取10条数据，这是第几页
    private CallOutDialog dialog;//item点击弹窗
    private CallLogLoadingDialog dialogLoading;//载入弹窗
    private CallLogDao callLogDao;//请求服务器的封装方法类

    List<CallLogMatchEntity> callLogMatchEntitylist;//从服务器返回的当前联系人的电话数据

    private int position = 0;//标记请求接口的第几条数据，当数据刷新是重置为0

    private int jurisdiction,jurisdiction4;

    private List<MoreJurisdictionEntity> listJuris;
    private CallLogEntity entity;
    private String clicks = "1";//1 ： 匹配成功    2： 无法匹配

    @Override
    public void init(Bundle savedInstanceState) {
        super.init(savedInstanceState);
        register();
        initView();
    }

    //初始化布局控件及监听
    private void initView() {
        jurisdiction = getIntent().getIntExtra("jurisdiction",1);
        callLogDao = new CallLogDaoImpl();
        lists = new ArrayList<>();
        listsNew = new ArrayList<>();
        listall = new ArrayList<>();

        topTitle.setText(getString(R.string.call_log_title));
        topBack.setOnClickListener(this);
        topMore.setOnClickListener(this);

        dialog = new CallOutDialog(this, R.style.DialogLoadingTheme,jurisdiction,jurisdiction4);
        dialogLoading = new CallLogLoadingDialog(this,R.style.DialogLoadingTheme);

        callLogListview.setOnRefreshOrLoadMoreListener(this);
        adapter = new CallLogAdapter(this);
        callLogListview.setAdapter(adapter);
        callLogListview.setOnItemClickListener(this);


        Log.v("token", CApplication.tokens);
    }

    private void getJurisdiction(String prefix) {
        callLogDao = new CallLogDaoImpl();
        BeauEventList.MoreJurisdictionEvent event = new BeauEventList.MoreJurisdictionEvent();
        callLogDao.getMoreJurisdiction(prefix, event);
    }


    public void onEventMainThread(BeauEventList.MoreJurisdictionEvent event) {
        if (event.isError()) {
            return;
        }
        listJuris = event.getData();
        for (MoreJurisdictionEntity moreJurisdictionEntity : listJuris) {
            if (moreJurisdictionEntity.objPrefix.equals("003")) {//联系人
                if (moreJurisdictionEntity.objstatus.equals("true")) {
                    if(moreJurisdictionEntity.permMap.add){
                        jurisdiction = 1;
                    }else{
                        jurisdiction = 2;
                    }
                } else {
                    jurisdiction = 3;
                }

            }
            if (moreJurisdictionEntity.objPrefix.equals("004")) {//潜在客户
                if (moreJurisdictionEntity.objstatus.equals("true")) {
                    if(moreJurisdictionEntity.permMap.add){
                        jurisdiction4 = 1;
                    }else{
                        jurisdiction4 = 2;
                    }
                } else {
                    jurisdiction4 = 3;
                }
            }
        }
        dialog = new CallOutDialog(this, R.style.DialogLoadingTheme,jurisdiction,jurisdiction4);
        if(clicks.equals("2")){//无法匹配
            dialog.setbt1(entity);
        }else {//匹配成功
            dialog.setbt2(entity);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        dialogLoading.show();
        dialogLoading.settext(getString(R.string.call_log_dialog_loading_match));
        Pager = 0;
        getCallLog(Pager);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_call_log;
    }


    //获取通话记录
    private void getCallLog(int pager) {
        if(pager == 0){
            lists.clear();
            listall.clear();
            position = 0;

            // 1.获得ContentResolver
            ContentResolver resolver = getContentResolver();
            // 2.利用ContentResolver的query方法查询通话记录数据库
            /**
             * @param uri 需要查询的URI，（这个URI是ContentProvider提供的）
             * @param projection 需要查询的字段
             * @param selection sql语句where之后的语句
             * @param selectionArgs ?占位符代表的数据
             * @param sortOrder 排序方式
             *
             */
            Cursor cursor = resolver.query(CallLog.Calls.CONTENT_URI, // 查询通话记录的URI
                    new String[]{CallLog.Calls.CACHED_NAME// 通话记录的联系人
                            , CallLog.Calls.NUMBER// 通话记录的电话号码
                            , CallLog.Calls.DATE// 通话记录的日期
                            , CallLog.Calls.DURATION// 通话时长
                            , CallLog.Calls.TYPE}// 通话类型
                    , null , null, CallLog.Calls.DEFAULT_SORT_ORDER// 按照时间逆序排列，最近打的最先显示
            );
            if(cursor == null){
                Toast.makeText(this, getString(R.string.call_log_nofind_record), Toast.LENGTH_SHORT).show();
                dialogLoading.dismiss();
                callLogListview.handlerLoadMoreFinish(true, false);
                callLogEmpty.setVisibility(View.VISIBLE);
                return;
            }
            int n = 0;
            // 3.通过Cursor获得数据
            while (cursor.moveToNext() && n < 50) {
                String name = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME));
                String number = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
                long dateLong = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE));
                String date = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date(dateLong));
                long duration = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.DURATION));
                int type = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.TYPE));

                listall.add(new CallLogEntity(name, number, date, duration + "", type, 3, " "));//默认不匹配
                n++;
            }
            if(cursor != null){
                cursor.close();
            }
            if (listall == null || listall.size() == 0) {
                Toast.makeText(this,  getString(R.string.call_log_nofind_record), Toast.LENGTH_SHORT).show();
                dialogLoading.dismiss();
                callLogListview.handlerLoadMoreFinish(true, false);
                callLogEmpty.setVisibility(View.VISIBLE);
                return;
            }
            callLogEmpty.setVisibility(View.GONE);
        }
        listsNew.clear();
        int max = listall.size() >= (pager+1)*10 ? (pager+1)*10 : listall.size();

        for(int i = pager*10 ; i < max ; i++){
            lists.add(listall.get(i));
        }

        if(pager == 0){
            getUrlMatch();
        }else{
            isMore();
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public void onClick(View v) {
        if (v == topBack) {
            finish();
        }
        if (v == topMore) {
            dialogLoading.show();
            dialogLoading.settext(getString(R.string.call_log_dialog_loading_refsh));
            Pager = 0;
            getCallLog(Pager);
        }

    }

    @Override
    public void onRefresh(PtrFrameLayout frame) {
        callLogListview.refreshComplete();

    }

    @Override
    public void onLoadMore(LoadMoreContainer frame) {
        Pager++;
        getCallLog(Pager);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
         entity = adapter.getItem(position);
        if(adapter.getItem(position).match == 1){//匹配成功
            clicks = "1";
            getJurisdiction("003,004");
        }else if(entity.match == 2){//多个匹配（电话匹配）

            String startTime = DateUtils.StringToString(entity.date);
            String endTime = DateUtils.addStartTime(startTime , Long.decode(entity.duration));

            Intent intent = new Intent(this, BeauListActivity.class);
            intent.putExtra(ExtraConstant.EXTRA_ID, "contact");
            intent.putExtra(ExtraConstant.EXTRA_NAME, "联系人");
            intent.putExtra("imageId", "cloudtab_must_003");
            intent.putExtra(ExtraConstant.EXTRA_URL, UrlManager.getManager()
                    .getNewRecordUrl("003"));
//            intent.putExtra("callLog", "addphone");//返回变成Home按钮并且添加电话活动
            intent.putExtra("CallName", entity.number);//通话人姓名
//            intent.putExtra("startTime", startTime);//事件开始时间
//            intent.putExtra("endTime", endTime);//事件结束时间
            startActivity(intent);

        }else if(entity.match == 3){//无法匹配
            clicks = "2";
            getJurisdiction("003,004");
        }else if(entity.match == 4){//多个匹配（名字匹配）
            String startTime = DateUtils.StringToString(entity.date);
            String endTime = DateUtils.addStartTime(startTime , Long.decode(entity.duration));

            Intent intent = new Intent(this, BeauListActivity.class);
            intent.putExtra(ExtraConstant.EXTRA_ID, "contact");
            intent.putExtra(ExtraConstant.EXTRA_NAME, "联系人");
            intent.putExtra("imageId", "cloudtab_must_003");
            intent.putExtra(ExtraConstant.EXTRA_URL, UrlManager.getManager()
                    .getNewRecordUrl("003"));
//            intent.putExtra("callLog", "addphone");//返回变成Home按钮并且添加电话活动
            intent.putExtra("CallName", entity.name);//活动名
//            intent.putExtra("startTime", startTime);//事件开始时间
//            intent.putExtra("endTime", endTime);//事件结束时间
            startActivity(intent);
        }
    }

    /**
     * 匹配返回接口，。处理匹配的规则 ：
     *
     *        如果返回错误error  无法匹配
     *       if（电话 = 系统电话）判断名字 if 名字相等 完全匹配   如果名字不相等 多个匹配之电话匹配
     *       else 电话不等于系统电话  多个匹配之名字匹配
     *
     * @param event
     */
    public void onEventMainThread(BeauEventList.CallLogMatchEvent event) {
        CallLogEntity entity = lists.get(position);
        if (event.isError()) {
            listsNew.add(new CallLogEntity(entity.name, entity.number, entity.date, entity.duration + "", entity.type, 3, " "));//不匹配-无id
            isMore();
            return;
        }
        callLogMatchEntitylist = event.getData();

        if(callLogMatchEntitylist == null || callLogMatchEntitylist.size() == 0){
            listsNew.add(new CallLogEntity(entity.name, entity.number, entity.date, entity.duration + "", entity.type, 3, " "));//不匹配-无id
        }else{
            int matchInt = 4;//默认为2多个匹配(名字匹配) 1为匹配成功  4多个匹配（名字匹配）
            String ids = " ";//匹配成功的id
            for(CallLogMatchEntity callLogMatchEntity : callLogMatchEntitylist){
                if( (callLogMatchEntity.shouji != null && (callLogMatchEntity.shouji).equals(entity.number)) || ( callLogMatchEntity.dianhua != null && (callLogMatchEntity.dianhua).equals(entity.number)) ){
                    if(callLogMatchEntity.name != null && callLogMatchEntity.name.equals(entity.name)){//完全匹配
                        matchInt = 1;
                        ids = callLogMatchEntity.id;
                        break;
                    }else{//电话多个匹配
                        matchInt = 2;
                    }
                }else {//名字多个匹配
                    if(matchInt != 2 && matchInt != 1){
                        matchInt = 4;
                    }
                }
            }
            listsNew.add(new CallLogEntity(entity.name, entity.number, entity.date, entity.duration + "", entity.type, matchInt, ids));
        }

        isMore();

    }

    //判断是否需要继续匹配
    private void isMore(){
        if (position < lists.size() - 1) {//如果后面还有记录，继续匹配接口判断
            position++;
            getUrlMatch();
        }else{
            listviewState();
            if(Pager < 5){//初次加载完毕弹窗消失
                adapter.addData(listsNew);
            }
        }
    }

    private void getUrlMatch(){//匹配接口请求
        BeauEventList.CallLogMatchEvent event = new BeauEventList.CallLogMatchEvent();
        if(lists.get(position).number == null && lists.get(position).name == null){//如果手机号和名字都为空，不必请求接口直接返回不匹配（这种情况正常不会出现）
             listsNew.add(new CallLogEntity(lists.get(position).name, lists.get(position).number, lists.get(position).date, lists.get(position).duration + "", lists.get(position).type, 3, " "));//不匹配-无id
            isMore();
        }else{
            callLogDao.CallLogMatch("Contact", "(name = '" + lists.get(position).name + "' or dianhua = '" + lists.get(position).number + "' or shouji = '"+ lists.get(position).number +"')", "name,shouji,dianhua", event);
        }
    }

    private void listviewState(){
        if (Pager == 0) {
            if (listsNew.size() < 9) {
                callLogListview.handlerLoadMoreFinish(false, false);
            } else {
                callLogListview.handlerLoadMoreFinish(false, true);//两个参数：是否是数据为空，是否还有更多(第一次加载数据还有更多)
            }
            dialogLoading.dismiss();
            adapter.clear();
        } else {
            if (listsNew.size() < 9 || Pager >= 5) {
                callLogListview.handlerLoadMoreFinish(false, false);
            } else {
                callLogListview.handlerLoadMoreFinish(false, true);//两个参数：是否是数据为空，是否还有更多
            }
        }
    }

    @Override
    public void register() {
        EventEngine.register(this);
    }

    @Override
    public void unRegister() {
        EventEngine.uregister(this);
    }

    @Override
    protected void onDestroy() {
        unRegister();
        super.onDestroy();
    }
}
